<?php

/**
 * This is the model class for table "{{stat_counter}}".
 *
 * The followings are the available columns in table '{{stat_counter}}':
 * @property integer $id
 * @property integer $year
 * @property integer $month
 * @property integer $day
 * @property integer $hour
 * @property integer $weekday
 * @property integer $pageviews
 * @property integer $visitors
 * @property integer $online_average
 */
class StatCounter extends CActiveRecord
{

    const DATA_DAILY     = 'daily';
    const DATA_WEEKDAILY = 'weekdaily';
    const DATA_HOURLY    = 'hourly';
    const DATA_MONTHY    = 'monthy';
    const DATA_YEARLY    = 'yearly';
    const TYPE_VISITORS  = 'visitors';
    const TYPE_VIEWS     = 'pageviews';

    public $todayVisitors = 0;
    public $totalVisitors = 0;
    public $sumVisitors   = 0;
    public $todayViews    = 0;
    public $totalViews    = 0;
    public $sumViews      = 0;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return StatCounter the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{stat_counter}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('year, month, day, hour, weekday, pageviews', 'required'),
            array('year, month, day, hour, weekday, pageviews, visitors, online_average', 'numerical', 'integerOnly' => true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, year, month, day, hour, weekday, pageviews, visitors, online_average', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'             => 'ID',
            'year'           => Yii::t('main', 'Year'),
            'month'          => Yii::t('main', 'Month'),
            'day'            => Yii::t('main', 'Day'),
            'hour'           => Yii::t('main', 'Hour'),
            'weekday'        => Yii::t('main', 'Weekday'),
            'pageviews'      => Yii::t('main', 'Pageviews'),
            'visitors'       => Yii::t('main', 'Visitors'),
            'online_average' => Yii::t('main', 'Online Average'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('year', $this->year);
        $criteria->compare('month', $this->month);
        $criteria->compare('day', $this->day);
        $criteria->compare('hour', $this->hour);
        $criteria->compare('weekday', $this->weekday);
        $criteria->compare('pageviews', $this->pageviews);
        $criteria->compare('visitors', $this->visitors);
        $criteria->compare('online_average', $this->online_average);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function today($type = self::TYPE_VIEWS)
    {
        $year  = date('Y');
        $month = date('m');
        $day   = date('d');
        return self::day($type, $year, $month, $day);
    }

    public static function day($type, $year, $month, $day)
    {
        $select    = "day, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $condition = "year=:year AND month=:month AND day=:day";
        $group     = 'year, month, day';

        $params[':year']  = $year;
        $params[':month'] = $month;
        $params[':day']   = $day;

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;

        $counter = self::model()->find($criteria);
        if ($counter == NULL)
        {
            return 0;
        }

        if ($type == self::TYPE_VIEWS)
        {
            return $counter->sumViews;
        }
        elseif ($type == self::TYPE_VISITORS)
        {
            return $counter->sumVisitors;
        }
    }

    public static function thisMonth($type = self::TYPE_VIEWS)
    {
        $year  = date('Y');
        $month = date('m');
        return self::month($type, $year, $month);
    }

    public static function month($type, $year, $month)
    {
        $select    = "month, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $condition = "year=:year AND month=:month";
        $group     = 'year, month';

        $params[':year']  = $year;
        $params[':month'] = $month;

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;

        $counter = self::model()->find($criteria);
        if ($counter == NULL)
        {
            return 0;
        }

        if ($type == self::TYPE_VIEWS)
        {
            return $counter->sumViews;
        }
        elseif ($type == self::TYPE_VISITORS)
        {
            return $counter->sumVisitors;
        }
    }

    public static function thisYear($type = self::TYPE_VIEWS)
    {
        $year = date('Y');
        return self::year($type, $year);
    }

    public static function year($type, $year)
    {
        $select    = "year, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $condition = "year=:year";
        $group     = 'year';

        $params[':year'] = $year;

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;

        $counter = self::model()->find($criteria);
        if ($counter == NULL)
        {
            return 0;
        }

        if ($type == self::TYPE_VIEWS)
        {
            return $counter->sumViews;
        }
        elseif ($type == self::TYPE_VISITORS)
        {
            return $counter->sumVisitors;
        }
    }

    public static function total($type = self::TYPE_VIEWS)
    {
        $select = "SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";

        $criteria         = new CDbCriteria();
        $criteria->select = $select;

        $counter = self::model()->find($criteria);
        if ($counter == NULL)
        {
            return 0;
        }

        if ($type == self::TYPE_VIEWS)
        {
            return $counter->sumViews;
        }
        elseif ($type == self::TYPE_VISITORS)
        {
            return $counter->sumVisitors;
        }
    }

    public static function getStat($type = self::DATA_DAILY, $year = NULL, $month = NULL, $day = NULL, $hour = NULL)
    {
        $year  = ($year == NULL) ? date('Y') : $year;
        $month = ($month == NULL) ? date('m') : $month;
        $day   = ($day == NULL) ? date('d') : $day;
        $hour  = ($hour == NULL) ? date('w') : $hour;

        $select    = "";
        $condition = "";
        $group     = "";
        $params    = array();
        switch ($type)
        {
            case self::DATA_HOURLY:
                $select           = "hour, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
                $condition        = "year=:year AND month=:month AND day=:day";
                $group            = 'year, month, day, hour';
                $params[':year']  = $year;
                $params[':month'] = $month;
                $params[':day']   = $day;
                break;
            case self::DATA_DAILY:
                $select           = "day, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
                $condition        = "year=:year AND month=:month";
                $params[':year']  = $year;
                $group            = 'year, month, day';
                $params[':month'] = $month;
                break;
            case self::DATA_WEEKDAILY:
                $select           = "weekday, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
                $condition        = "year=:year AND month=:month";
                $params[':year']  = $year;
                $group            = 'year, month, weekday';
                $params[':month'] = $month;
                break;
            case self::DATA_MONTHY:
                $condition        = "year=:year";
                $group            = 'year, month';
                $params[':year']  = $year;
                break;
            case self::DATA_YEARLY:
                $condition        = "";
                $group            = 'year';
                break;

            default:
                break;
        }

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;
        $counter             = self::model()->findAll($criteria);

        return $counter;
    }

    public static function hourly($start = null, $end = null)
    {
        $select    = "hour, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $group     = 'year, month, day, hour';
        $condition = "";
        $params    = array();

        if ($start != null && $end != null)
        {
            $condition .= "year >= :ys AND year <= :ye ";
            $condition .= "month >= :ms AND month <= :me ";
            $condition .= "day >= :ds AND day <= :de";

            $params[':ys'] = date('Y', $start);
            $params[':ms'] = date('m', $start);
            $params[':ds'] = date('d', $start);

            $params[':me'] = date('m', $end);
            $params[':ye'] = date('Y', $end);
            $params[':de'] = date('d', $end);
        }

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;
        $counter             = self::model()->findAll($criteria);

        return $counter;
    }

    public static function weekdaily($start = null, $end = null)
    {
        $select    = "weekday, SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $group     = 'year, month, weekday';
        $condition = "";
        $params    = array();

        if ($start != null && $end != null)
        {
            $condition .= "year >= :ys AND year <= :ye ";
            $condition .= "month >= :ms AND month <= :me ";
            $condition .= "day >= :ds AND day <= :de";

            $params[':ys'] = date('Y', $start);
            $params[':ms'] = date('m', $start);
            $params[':ds'] = date('d', $start);

            $params[':me'] = date('m', $end);
            $params[':ye'] = date('Y', $end);
            $params[':de'] = date('d', $end);
        }

        $criteria            = new CDbCriteria();
        $criteria->select    = $select;
        $criteria->condition = $condition;
        $criteria->params    = $params;
        $criteria->group     = $group;
        $counter             = self::model()->findAll($criteria);

        return $counter;
    }

    public static function run()
    {
        $cri            = new CDbCriteria();
        $cri->condition = 'year= :y AND month=:m AND day=:d AND hour=:h';
        $cri->params    = array(
            ':y' => date('Y'),
            ':m' => date('m'),
            ':d' => date('d'),
            ':h' => date('H'),
        );
        $counter        = self::model()->find($cri);
        if ($counter == null)
        {
            $counter            = new StatCounter();
            $counter->year      = date('Y');
            $counter->month     = date('m');
            $counter->day       = date('d');
            $counter->hour      = date('H');
            $counter->weekday   = date('w');
            $counter->pageviews = 0;
        }

        $thisHour          = strtotime(date("Y-m-d H:00:00"));
        $counter->visitors = StatOnline::countVisitor($thisHour);
        $counter->pageviews++;
        $counter->save();
    }

    static public function getViewUrl()
    {
        return Yii::app()->controller->createUrl('statistic/index', array(
                    'lang' => Yii::app()->controller->lang
        ));
    }

    static public function getCode()
    {
        $url        = Yii::app()->request->requestUri;
        $refer      = Yii::app()->request->urlReferrer;
        $token      = self::getToken(array($url, $refer));
        $collectUrl = Yii::app()->createUrl('frontend/statistic/collect');
        $code       = "<script> var data={url:'$url',refer:'$refer',token:'$token'};$.ajax({url:'$collectUrl',data:data})</script>";
        return $code;
    }

    static public function getToken($data)
    {
        return md5(implode("+", $data) . 'qymzsTIXAEyU');
    }

    public static function countVisitorsByDate($time_stamp)
    {
        $cri            = new CDbCriteria();
        $cri->select    = "SUM(`visitors`) AS `sumVisitors`, SUM(`pageviews`) AS `sumViews`";
        $cri->condition = 'year=:y AND month=:m AND day=:d';
        $cri->params    = array(
            ':d' => date('d', $time_stamp),
            ':m' => date('m', $time_stamp), //integer
            ':y' => date('Y', $time_stamp),
        );
        $count_visitors = StatCounter::model()->find($cri);
        if ($count_visitors != NULL)
        {
            return $count_visitors->sumVisitors;
        }
        else
        {
            return 0;
        }
    }

}
